package com.prd.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.api.RemoteUserService;
import com.prd.config.LoginInterceptor;
import com.prd.constant.CheckStatus;
import com.prd.constant.IsStatus;
import com.prd.dto.SupervisorVo;
import com.prd.mapper.EntTaskMapper;
import com.prd.model.*;
import com.prd.service.*;
import com.prd.util.StringsUtils;
import com.prd.util.UserInfoUtil;
import com.prd.vo.EntTaskVo;
import com.prd.vo.ExecutiveStageTaskVo;
import com.prd.vo.ExecutiveStageTaskVo;
import com.prd.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EntTaskServiceImpl extends ServiceImpl<EntTaskMapper, EntTask> implements EntTaskService {

    @Autowired
    private EntTaskMapper entTaskMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private EntTaskCheckService entTaskCheckService;

    @Autowired
    private EntTaskStageService entTaskStageService;

    @Autowired
    private EntTaskCollectService entTaskCollectService;

    @Autowired
    private EntTaskPeriodicService entTaskPeriodicService;

    @Override
    public int insertInfo(EntTask entTask) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        BeanUtils.copyProperties(UserInfoUtil.recordInfo(loginUser.getId(), loginUser.getName(), true), entTask);
        entTask.setStatus(CheckStatus.ONE.getCode());
        entTask.setExecute(1);
        if (entTask.getDecompose() == null) {
            entTask.setDecompose(0);
        }
        entTask.setRevocation(IsStatus.TWO.getCode());
        entTask.setNumber(String.valueOf(System.nanoTime()));
        return entTaskMapper.insert(entTask);
    }

    @Override
    public int updateInfo(EntTask entTask) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        BeanUtils.copyProperties(UserInfoUtil.recordInfo(loginUser.getId(), loginUser.getName(), false), entTask);
        return entTaskMapper.updateById(entTask);
    }

    @Override
    public List<EntTask> listInfo(String day, Integer type) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        LambdaQueryWrapper<EntTask> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.apply(StringUtils.isNotBlank(day), "DATE(end_time) = {0}", day);
        //1:我发起
        if (type == 1) {
            lambdaQueryWrapper.eq(EntTask::getCreateId, loginUser.getId());
        } else if (type == 2 || type == 3) {
            lambdaQueryWrapper.eq(EntTask::getEnact, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntTask::getOverall, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntTask::getSupervisor, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntTask::getRedact, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntTask::getAudit, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntTask::getRatify, loginUser.getId());
            lambdaQueryWrapper.or().apply("find_in_set({0},make)", loginUser.getId());
//        2：我接收
            if (type == 2) {
            }
//        3：执行中
            if (type == 3) {
                lambdaQueryWrapper.eq(EntTask::getExecute, 2);
            }
        } else {
            throw new RuntimeException("找不到对应的编号！");
        }
        List<EntTask> listEntTask = entTaskMapper.selectList(lambdaQueryWrapper);

        listEntTask.stream().forEach(item -> {
            List<Long> arrayList = new ArrayList<>();
            List<Long> enacts = Arrays.asList(StringsUtils.convert(item.getEnact().split(",")));
            List<Long> overalls = Arrays.asList(StringsUtils.convert(item.getOverall().split(",")));
            List<Long> supervisors = Arrays.asList(StringsUtils.convert(item.getSupervisor().split(",")));
            arrayList.addAll(enacts);
            arrayList.addAll(overalls);
            arrayList.addAll(supervisors);
            arrayList.stream().distinct().collect(Collectors.toList());
            List<UserVo> listUser = remoteUserService.listInfo(arrayList.toArray(new Long[arrayList.size()])).getData();
            if (listUser != null && listUser.size() > 0) {
                for (UserVo userVo : listUser) {
                    if (enacts.contains(userVo.getId())) {
                        item.setEnact(userVo.getName());
                    }
                    if (overalls.contains(userVo.getId())) {
                        item.setOverall(userVo.getName());
                    }
                    if (supervisors.contains(userVo.getId())) {
                        item.setSupervisor(userVo.getName());
                    }
                }
            }
        });
        return listEntTask;
    }

    @Override
    public EntTaskVo details(Long id) {
        EntTaskVo entTaskVo = new EntTaskVo();
        EntTask entTask = entTaskMapper.selectById(id);
        if (entTask == null) {
            throw new RuntimeException("记录没有找到！");
        }
        BeanUtils.copyProperties(entTask, entTaskVo);
        List<Long> arrayList = new ArrayList<>();
        List<Long> enacts = Arrays.asList(StringsUtils.convert(entTask.getEnact().split(",")));
        List<Long> overalls = Arrays.asList(StringsUtils.convert(entTask.getOverall().split(",")));
        List<Long> supervisors = Arrays.asList(StringsUtils.convert(entTask.getSupervisor().split(",")));

        List<Long> redacts = Arrays.asList(StringsUtils.convert(entTask.getRedact().split(",")));
        List<Long> audits = Arrays.asList(StringsUtils.convert(entTask.getAudit().split(",")));
        List<Long> ratifys = Arrays.asList(StringsUtils.convert(entTask.getRatify().split(",")));
        List<Long> makes = Arrays.asList(StringsUtils.convert(entTask.getMake().split(",")));
        arrayList.addAll(enacts);
        arrayList.addAll(overalls);
        arrayList.addAll(supervisors);

        arrayList.addAll(redacts);
        arrayList.addAll(audits);
        arrayList.addAll(ratifys);
        arrayList.addAll(makes);
        arrayList.stream().distinct().collect(Collectors.toList());
        List<UserVo> listUser = remoteUserService.listInfo(arrayList.toArray(new Long[arrayList.size()])).getData();
        if (listUser != null && listUser.size() > 0) {
            List<String> makeList = new ArrayList<>();
            for (UserVo userVo : listUser) {
                if (enacts.contains(userVo.getId())) {
                    entTaskVo.setEnact(userVo.getName());
                }
                if (overalls.contains(userVo.getId())) {
                    entTaskVo.setOverall(userVo.getName());
                }
                if (supervisors.contains(userVo.getId())) {
                    entTaskVo.setSupervisor(userVo.getName());
                }
                if (redacts.contains(userVo.getId())) {
                    entTaskVo.setRedact(userVo.getName());
                }
                if (audits.contains(userVo.getId())) {
                    entTaskVo.setAudit(userVo.getName());
                }
                if (ratifys.contains(userVo.getId())) {
                    entTaskVo.setRatify(userVo.getName());
                }
                if (makes.contains(userVo.getId())) {
                    makeList.add(userVo.getName());
                }
            }
            entTaskVo.setMakes(makeList);
        }
        return entTaskVo;
    }

    @Override
    public JSONArray jurisdiction(Long taskId) {
        JSONArray jsonArray = new JSONArray();
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        EntTask entTask = entTaskMapper.selectById(taskId);
        if (entTask == null) {
            throw new RuntimeException("记录没有找到！");
        }
        List<Long> enacts = Arrays.asList(StringsUtils.convert(entTask.getEnact().split(",")));
        List<Long> overalls = Arrays.asList(StringsUtils.convert(entTask.getOverall().split(",")));
        List<Long> supervisors = Arrays.asList(StringsUtils.convert(entTask.getSupervisor().split(",")));
        if (enacts.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "enact");
            jsonObject.put("name", "目标制定人");
            jsonArray.add(jsonObject);
        }
        if (overalls.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "overall");
            jsonObject.put("name", "总负责人");
            jsonArray.add(jsonObject);
        }
        if (supervisors.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "supervisor");
            jsonObject.put("name", "督导负责人");
            jsonArray.add(jsonObject);
        }
        List<Long> redacts = Arrays.asList(StringsUtils.convert(entTask.getRedact().split(",")));
        List<Long> audits = Arrays.asList(StringsUtils.convert(entTask.getAudit().split(",")));
        List<Long> ratifys = Arrays.asList(StringsUtils.convert(entTask.getRatify().split(",")));
//        List<Long> makes = Arrays.asList(StringsUtils.convert(entTask.getMake().split(",")));
        if (redacts.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "redact");
            jsonObject.put("name", "编辑");
            jsonArray.add(jsonObject);
        }
        if (audits.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "audit");
            jsonObject.put("name", "审核");
            jsonArray.add(jsonObject);
        }
        if (ratifys.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "ratify");
            jsonObject.put("name", "批准");
            jsonArray.add(jsonObject);
        }
//        if (makes.contains(loginUser.getId())) {
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("code", "make");
//            jsonObject.put("name", "抄送");
//            jsonArray.add(jsonObject);
//        }
        return jsonArray;
    }

    @Override
    public int pass(EntTaskCheck entTaskCheck) {
        EntTask entTask = entTaskMapper.selectById(entTaskCheck.getTaskId());
        if (entTask == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entTask.setStatus(entTaskCheck.getType());
        entTaskCheckService.insertInfo(entTaskCheck);
        return updateInfo(entTask);
    }

    @Override
    public int execute(Long taskId) {
        EntTask entTask = entTaskMapper.selectById(taskId);
        if (entTask == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entTask.setResolve(1);
        entTask.setExecute(2);
        return updateInfo(entTask);
    }

    @Override
    public int executeResolve(EntTaskStage entTaskStage) {
        EntTask entTask = entTaskMapper.selectById(entTaskStage.getTaskId());
        if (entTask == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entTask.setResolve(2);
        entTask.setExecute(2);
        entTaskStageService.insertInfo(entTaskStage);
        return updateInfo(entTask);
    }

    @Override
    public ExecutiveStageTaskVo listExecutiveNoStage(Long taskId) {
        ExecutiveStageTaskVo executiveStageTaskVo = new ExecutiveStageTaskVo();
        LambdaQueryWrapper<EntTaskPeriodic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EntTaskPeriodic::getTaskId, taskId);
        EntTaskPeriodic TaskPeriodic = entTaskPeriodicService.getOne(queryWrapper);
        executiveStageTaskVo.setTaskPeriodic(TaskPeriodic);

        LambdaQueryWrapper<EntTaskCollect> queryWrapperCollect = new LambdaQueryWrapper<>();
        queryWrapperCollect.eq(EntTaskCollect::getTaskId, taskId);
        EntTaskCollect TaskCollect = entTaskCollectService.getOne(queryWrapperCollect);
        executiveStageTaskVo.setTaskCollect(TaskCollect);
        return executiveStageTaskVo;
    }

    @Override
    public ExecutiveStageTaskVo listExecutiveStage(Long stageId) {
        ExecutiveStageTaskVo executiveStageTaskVo = new ExecutiveStageTaskVo();
        LambdaQueryWrapper<EntTaskPeriodic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EntTaskPeriodic::getStageId, stageId);
        EntTaskPeriodic TaskPeriodic = entTaskPeriodicService.getOne(queryWrapper);
        executiveStageTaskVo.setTaskPeriodic(TaskPeriodic);

        LambdaQueryWrapper<EntTaskCollect> queryWrapperCollect = new LambdaQueryWrapper<>();
        queryWrapperCollect.eq(EntTaskCollect::getStageId, stageId);
        EntTaskCollect TaskCollect = entTaskCollectService.getOne(queryWrapperCollect);
        executiveStageTaskVo.setTaskCollect(TaskCollect);
        return executiveStageTaskVo;
    }

    @Override
    public int addDecompose(EntTask entTask) {
        EntTask entGocal1 = entTaskMapper.selectById(entTask.getTaskId());
        if (entGocal1 == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entTask.setEnact(entGocal1.getEnact());
        entTask.setSupervisor(entGocal1.getSupervisor());
        entTask.setRedact(entGocal1.getRedact());
        entTask.setAudit(entGocal1.getAudit());
        entTask.setRatify(entGocal1.getRatify());
        entTask.setMake(entGocal1.getMake());
        return insertInfo(entTask);
    }

    @Override
    public List<EntTaskVo> listDecompose(Integer decompose, Long taskId) {
        List<EntTaskVo> list = new ArrayList<>();
        LambdaQueryWrapper<EntTask> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EntTask::getDecompose, decompose);
        lambdaQueryWrapper.eq(EntTask::getTaskId, taskId);
        List<EntTask> listEntTask = entTaskMapper.selectList(lambdaQueryWrapper);
        for (EntTask entTask : listEntTask) {
            list.add(details(entTask.getId()));
        }
        return list;
    }

    @Override
    public int updateDuty(EntTask entTask) {
        EntTask entTask1 = entTaskMapper.selectById(entTask.getId());
        if (entTask1 == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entTask1.setOverall(entTask.getOverall());
        entTask1.setReasons(entTask.getReasons());
        return updateInfo(entTask);
    }

    @Override
    public int addSupervisor(SupervisorVo supervisorVo) {
        EntTask entTask = entTaskMapper.selectById(supervisorVo.getId());
        if (entTask == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entTask.setSupervisorReach(supervisorVo.getReach());
        entTask.setSupervisorGist(supervisorVo.getGist());
        entTask.setSupervisorContent(supervisorVo.getContent());
        entTask.setSupervisorRecord(supervisorVo.getRecord());
        entTask.setSupervisorPicture(supervisorVo.getPicture());
        return updateInfo(entTask);
    }

    @Override
    public int revocation(Long taskId) {
        EntTask entTask = entTaskMapper.selectById(taskId);
        if (entTask == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entTask.setRevocation(IsStatus.ONE.getCode());
        return updateInfo(entTask);
    }

    @Override
    public int addMake(Long taskId, Long[] makes) {
        EntTask entTask = entTaskMapper.selectById(taskId);
        if (entTask == null) {
            throw new RuntimeException("记录没有找到！");
        }
        if (StringUtils.isNotBlank(entTask.getMake())) {
            entTask.setMake(entTask.getMake() + "," + makes.toString());
        } else {
            entTask.setMake(makes.toString());
        }
        return updateInfo(entTask);
    }
}
